package kata21;

public class MyArrayList<E> implements ISimpleList<E> {

    private Object[] data;

    private int size;

    public MyArrayList(){
        this(16);
    }

    public  MyArrayList(int capacity){
        data = new Object[capacity];
    }


    @Override
    public void add(E e) {
        if(size == data.length){
            //扩容
            int capacity = size * 2;
            Object[] newArray = new Object[capacity];
            System.arraycopy(data,0,newArray,0,size);
            data = newArray;
        }
        data[size] = e;
        ++size;
    }

    @Override
    public E find(E e) {
        for (Object obj : data) {
            if(e.equals(obj)){
                return (E)obj;
            }
        }
        return null;
    }

    @Override
    public void delete(E e) {
        //
        Integer index = null;
        for (int i = 0; i < data.length; i++) {
            if(e.equals(data[i])){
                index = i;
            }
        }
        //
        if(index != null){
            Object[] newArray = new Object[data.length];
            //拷贝前半部分数组
            System.arraycopy(data,0,newArray,0,index);
            //拷贝后半部分数组
            System.arraycopy(data,(index + 1),newArray,index,size);
            data = newArray;
            --size;
        }
    }

    @Override
    public String values() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        int poolEndIndex = (size -1);
        for (int i = 0; i < size;i++) {
            sb.append(data[i]);
            if(i != poolEndIndex){
                sb.append(", ");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
